import {
  getMealPlanDetail,
  createMealPlan,
  updateMealPlan,
  deleteMealPlan,
  getPlanTemplates,
  saveAsTemplate,
  createFromTemplate
} from '@/api/mealPlan'
import request from '@/config/axios'
import { getApiPath } from '@/config/api'

export default {
  namespaced: true,

  state: {
    mealPlans: [],
    currentPlan: null,
    recommendedPlan: null,
    templates: [],
    loading: false,
    total: 0
  },

  mutations: {
    SET_MEAL_PLANS(state, { list, total }) {
      state.mealPlans = list
      state.total = total
    },
    SET_CURRENT_PLAN(state, plan) {
      state.currentPlan = plan
    },
    SET_RECOMMENDED_PLAN(state, plan) {
      state.recommendedPlan = plan
    },
    SET_TEMPLATES(state, templates) {
      state.templates = templates
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    UPDATE_PLAN(state, { id, plan }) {
      const index = state.mealPlans.findIndex(p => p.id === id)
      if (index !== -1) {
        state.mealPlans[index] = { ...state.mealPlans[index], ...plan }
      }
    },
    REMOVE_PLAN(state, id) {
      state.mealPlans = state.mealPlans.filter(p => p.id !== id)
    }
  },

  actions: {
    // 获取膳食计划列表
    async getMealPlans({ commit }, params = {}) {
      try {
        const userId = localStorage.getItem('userId')
        if (!userId) {
          throw new Error('用户ID不存在')
        }

        const res = await request({
          url: getApiPath('MEAL_PLANS'),
          method: 'get',
          params: {
            userId: parseInt(userId),
            page: params.page || 1,
            pageSize: params.pageSize || 10
          }
        })

        if (res.code === 200 && res.data) {
          commit('SET_MEAL_PLANS', res.data)
          return res.data
        }
        throw new Error(res.message || '获取膳食计划失败')
      } catch (error) {
        console.error('获取膳食计划失败:', error)
        if (error.message === '用户ID不存在') {
          commit('CLEAR_MEAL_PLANS')
        }
        throw error
      }
    },

    // 获取膳食计划详情
    async getMealPlanDetail({ commit }, id) {
      try {
        const res = await getMealPlanDetail(id)
        commit('SET_CURRENT_PLAN', res.data)
        return res
      } catch (error) {
        console.error('获取膳食计划详情失败:', error)
        throw error
      }
    },

    // 创建膳食计划
    async createMealPlan({ dispatch }, data) {
      try {
        const res = await createMealPlan(data)
        await dispatch('getMealPlans')
        return res
      } catch (error) {
        console.error('创建膳食计划失败:', error)
        throw error
      }
    },

    // 更新膳食计划
    async updateMealPlan({ commit }, { id, data }) {
      try {
        const res = await updateMealPlan(id, data)
        commit('UPDATE_PLAN', { id, plan: res.data })
        return res
      } catch (error) {
        console.error('更新膳食计划失败:', error)
        throw error
      }
    },

    // 删除膳食计划
    async deleteMealPlan({ commit }, id) {
      try {
        await deleteMealPlan(id)
        commit('REMOVE_PLAN', id)
      } catch (error) {
        console.error('删除膳食计划失败:', error)
        throw error
      }
    },

    // 获取推荐膳食计划
    async getRecommendedPlan({ commit }) {
      try {
        commit('SET_LOADING', true)
        const userId = localStorage.getItem('userId')
        if (!userId) {
          throw new Error('用户未登录')
        }

        const res = await request({
          url: getApiPath('RECOMMENDED_PLAN'),
          method: 'get',
          params: {
            userId: parseInt(userId)
          }
        })

        if (res.code === 200 && res.data) {
          commit('SET_RECOMMENDED_PLAN', res.data)
          return res.data
        }
        throw new Error(res.message || '获取推荐计划失败')
      } catch (error) {
        console.error('获取推荐计划失败:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 获取计划模板列表
    async getPlanTemplates({ commit }) {
      try {
        const res = await getPlanTemplates()
        commit('SET_TEMPLATES', res.data)
        return res
      } catch (error) {
        console.error('获取计划模板失败:', error)
        throw error
      }
    },

    // 保存为模板
    async saveAsTemplate({ dispatch }, data) {
      try {
        const res = await saveAsTemplate(data)
        await dispatch('getPlanTemplates')
        return res
      } catch (error) {
        console.error('保存模板失败:', error)
        throw error
      }
    },

    // 从模板创建计划
    async createFromTemplate({ dispatch }, templateId) {
      try {
        const res = await createFromTemplate(templateId)
        await dispatch('getMealPlans')
        return res
      } catch (error) {
        console.error('从模板创建计划失败:', error)
        throw error
      }
    }
  }
} 